import axios from "axios";

// API 基础URL
const API_BASE_URL = "http://localhost:8082"; // 替换成你的Spring Boot后端地址

// 创建 axios 实例 - JSON格式
const jsonClient = axios.create({
  baseURL: API_BASE_URL,
  timeout: 10000,
  headers: {
    "Content-Type": "application/json",
  },
});

// 创建 axios 实例 - 表单格式
const formClient = axios.create({
  baseURL: API_BASE_URL,
  timeout: 10000,
  headers: {
    "Content-Type": "application/x-www-form-urlencoded",
  },
});

// 将对象转换为URL参数格式
const convertToFormData = (data) => {
  const params = new URLSearchParams();
  for (const key in data) {
    if (data[key] != null) {
      params.append(key, data[key]);
    }
  }
  return params;
};

// 响应拦截器 - 统一处理错误
const responseInterceptor = (response) => response.data;
const errorInterceptor = (error) => {
  if (error.response) {
    return Promise.reject(error.response.data);
  }
  return Promise.reject(new Error("请求失败，请检查网络连接"));
};

jsonClient.interceptors.response.use(responseInterceptor, errorInterceptor);
formClient.interceptors.response.use(responseInterceptor, errorInterceptor);

// GET 请求封装
export const get = (url, params = {}) => {
  return jsonClient.get(url, { params });
};

// POST 请求封装 - 支持两种格式
export const post = (url, data = {}, useJson = false) => {
  if (useJson) {
    return jsonClient.post(url, data);
  }
  return formClient.post(url, convertToFormData(data));
};

// PUT 请求封装 - 支持两种格式
export const put = (url, data = {}, useJson = false) => {
  if (useJson) {
    return jsonClient.put(url, data);
  }
  return formClient.put(url, convertToFormData(data));
};

// DELETE 请求封装
export const del = (url) => {
  return jsonClient.delete(url);
};
